using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
using Placid.Core;
using Placid.PivotSourceImpl;

namespace PlacidTest
{
    public partial class TestForm : Form
    {
        private int _lastRow;
        private int _lastColumn;
        private DataTable _sourceDt;
        private Pivot _pivot;

        public TestForm()
        {            
            InitializeComponent();
            _lastRow = 0;
            _lastColumn = 0;
            _pivot = new Pivot();
            _sourceDt = new DataTable();
            dgvSource.DataSource = _sourceDt;
        }

        public void SetDataSource(DataTable dt, int lastRow, int lasColumn)
        {
            dgvPivot.DataSource = null;
            dgvPivot.DataSource = dt;
            _lastRow = lastRow;
            _lastColumn = lasColumn;
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            DataGridViewAdvancedCellBorderStyle st = DataGridViewAdvancedCellBorderStyle.Inset;
            e.AdvancedBorderStyle.All = st;

            if (e.RowIndex <= _lastRow && e.ColumnIndex <= _lastColumn)
            {
                e.CellStyle.BackColor = dgvPivot.BackgroundColor;
                e.AdvancedBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None;
            }
            else if (e.RowIndex <= _lastRow || e.ColumnIndex <= _lastColumn)
            {
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                e.CellStyle.BackColor = Color.FromKnownColor(KnownColor.Control);
                if (e.Value == DBNull.Value)
                {
                    if (e.RowIndex <= _lastRow)
                    {
                        e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None;
                        e.AdvancedBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.None;
                    }
                    else if (e.ColumnIndex <= _lastColumn)
                    {
                        e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None;
                        e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None;
                    }
                }
                else
                {

                    e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None;
                    e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OdbcConnection conn = null;
            OdbcCommand com = null;
            OdbcDataAdapter dap = null;

            try {
                if(openFileDialog1.ShowDialog(this) == DialogResult.OK) {

                    textBox1.Text = openFileDialog1.FileName;

                    conn = new OdbcConnection("Driver={Microsoft Text Driver (*.txt; *.csv)};" +
                                                                    "Dbq=" + System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + ";" +
                                                                    "Extensions=asc,csv,tab,txt");
                    //OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + ";Extended Properties='Text;HDR=Yes;FMT=Delimited'")

                    ClearAll();

                    conn.Open();

                    com = new OdbcCommand("select * from " + System.IO.Path.GetFileName(openFileDialog1.FileName)+"", conn);
                    dap = new OdbcDataAdapter(com);
                    dap.Fill(_sourceDt);
                }
            } catch {
            } finally {
                if(conn != null) {
                    if(conn.State == ConnectionState.Open) conn.Close();
                    conn.Dispose();
                    conn = null;
                }

                if(com != null) { com.Dispose(); com = null; }
                if(dap != null) { dap.Dispose(); dap = null; }
            }

            FillColumnsList();
        }

        private void FillColumnsList()
        {
            foreach(DataColumn dc in _sourceDt.Columns) {
                listBox1.Items.Add(dc.ColumnName);
            }
        }

        private void ClearAll()
        {
            _pivot.Dispose();
            _sourceDt.Clear();
            _sourceDt.Columns.Clear();

            listBox1.Items.Clear();
            lbRows.Items.Clear();
            lbColumns.Items.Clear();
            lbMeasures.Items.Clear();
        }

        private bool GetSelectedSourceCol(ListBox lb, out string srcCol)
        {
            srcCol = lb.SelectedItem as string;
            return srcCol != null;
        }

        private void MoveSourceCol(ListBox desLb, string prefix)
        {
            string srcCol;
            if(GetSelectedSourceCol(listBox1, out srcCol)) {
                desLb.Items.Add(prefix+srcCol);
            }
        }

        private void MovebackSourceCol(ListBox srcLb)
        {
            string srcCol;
            if(GetSelectedSourceCol(srcLb, out srcCol)) {
                srcLb.Items.Remove(srcCol);
            }
        }

        private void btAddRow_Click(object sender, EventArgs e)
        {
            MoveSourceCol(lbRows,"");
        }

        private void btAddColumn_Click(object sender, EventArgs e)
        {
            MoveSourceCol(lbColumns,"");
        }

        private void btAddMeasureCount_Click(object sender, EventArgs e)
        {
            MoveSourceCol(lbMeasures, "COUNT| ");
        }

        private void btAddMeasureSum_Click(object sender, EventArgs e)
        {
            MoveSourceCol(lbMeasures, "SUM  | ");
        }

        private void lb_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListBox lb = sender as ListBox;
            if(lb != null && lb.SelectedIndex > -1 && lb.GetItemRectangle(lb.SelectedIndex).Contains(e.Location)) {
                    MovebackSourceCol(lb);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string mt;

            _pivot.Dispose();
            _pivot = new Pivot();

            foreach(string row in lbRows.Items) _pivot.Schema.AddRow(row);
            foreach(string col in lbColumns.Items) _pivot.Schema.AddColumn(col);
            foreach(string ms in lbMeasures.Items) {
                mt = ms.Substring(0, 5).Trim();
                _pivot.Schema.Addm(ms.Substring(7), mt);
            }

            _pivot.DSrc = new PivotSource(_sourceDt);
            _pivot.Update();
            SetDataSource(_pivot.GetResult(), _pivot.Schema.Columns.Count - 1, _pivot.Schema.Rows.Count - 1);
        }
    }
}